package jxau.jwgl.web.controller;

import jxau.jwgl.commons.WebData;
import jxau.jwgl.utils.ConvertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * ViewController
 *
 * @author LongShu 2017/06/05
 */
@Controller
public class ViewController extends BaseController implements ErrorController {
    private static Properties views;

    static {
        try (InputStream in = ViewController.class.getClassLoader().getResourceAsStream("views.properties")) {
            views = new Properties();
            if (in != null) {
                views.load(in);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取视图
     *
     * @param name 视图名称
     * @return 视图路径
     */
    public static String getView(String name) {
        String view = "error/404";// 默认404

        if (StringUtils.isNotBlank(name)) {
            view = views.getProperty(name, view);// 不存在则404
        }

        return view;
    }

    @GetMapping("/")
    public String index() {
        return "/index";
    }

    @RequestMapping("/view/{v}")
    public String view(@PathVariable(value = "v", required = false) String v) {
        String view = views.getProperty(v, "/error/404");
        logger.debug("v:{}, view:[{}]", v, view);
        return view;
    }

    @RequestMapping("/error/{code}")
    public String error(@PathVariable(required = false) String code, HttpServletResponse response) {
        logger.debug("code:{}", code);
        Integer keyCode = ConvertUtil.toInt(code, 404);
        String view = views.getProperty(code, "/error/404");
        if ("/error/404".equals(view)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else {
            response.setStatus(keyCode);
        }
        return view;
    }

    @RequestMapping("/error")
    @ResponseBody
    public Object errorHandle(HttpServletRequest request, HttpServletResponse response) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
        response.setStatus(statusCode);

        ControllerExceptionHandler.showUrl(request, statusCode);

        if (isAjax(request)) {
            return WebData.newError("出错啦!");
        } else {
            return new ModelAndView(getView(statusCode + "")).addObject("message", "出错啦!");
        }
    }

    @Override
    public String getErrorPath() {
        return "/error/error";
    }

}
